package store.web.servlet;

import store.domain.Account;
import store.domain.Product;
import store.service.AccountService;
import store.service.CatalogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

//实现用户登录
public class SignOnServlet extends HttpServlet {

    private static final String SIGN_ON_FORM = "/WEB-INF/jsp/account/signon.jsp";

    private String username;
    private String password;
    private String signOnMsg;

    protected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
        this.username = req.getParameter("username");
        this.password = req.getParameter("password");
        //用户输入有误跳转回登陆页面
        if(!isCorrect()){
            req.setAttribute("signOnMsg", this.signOnMsg);
            req.getRequestDispatcher(SIGN_ON_FORM).forward(req, resp);
        }else {

            //传给业务逻辑层进行处理
            AccountService accountService = new AccountService();
            Account loginAccount=accountService.getAccount(username, password);
            //用户名和密码是错误的

            if(loginAccount==null){
                this.signOnMsg="用户名或密码错误";
                req.getRequestDispatcher(SIGN_ON_FORM).forward(req, resp);
            }else{
                System.out.println("进入");
                loginAccount.setPassword(null);
                //登陆成功，跳转回首页。。。
                HttpSession session = req.getSession();
                session.setAttribute("loginAccount", loginAccount);
                resp.sendRedirect("mainForm");

                if(loginAccount.isListOption()){
                    CatalogService catalogService = new CatalogService();
                    List<Product> myList = catalogService.getProductListByCategory(loginAccount.getFavouriteCategoryId());
                    session.setAttribute("myList", myList);
                }
            }
        }
    }
    //校验用户输入正确性(只检验了不可为空)
    private boolean isCorrect(){
        if(this.username == null || this.username.equals("")){
            this.signOnMsg = "用户名不能为空";
            return false;
        }
        if(this.password == null || this.password.equals("")){
            this.signOnMsg = "密码不能为空";
            return false;
        }
        return true;
    }
}
